package com.yuyou.fn.common.util;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import java.util.concurrent.TimeUnit;

public class CacheUtils {

    /**
     *
     * @param expired 过期时间 单位秒
     * @param loader
     * @param <K>
     * @param <T>
     * @return
     */

    public static  <K,T> LoadingCache<K,Optional<T>> buildCache(long expired ,Function<K,T> loader ){
        return CacheBuilder.newBuilder().expireAfterAccess(expired , TimeUnit.SECONDS ).build(new CacheLoader<K, Optional<T>>() {
            @Override
            public Optional<T> load(K key) throws Exception {
                return Optional.fromNullable(loader.apply(key));
            }
        });
    }

    /**
     *
     * @param loader
     * @param <K>
     * @param <T>
     * @return
     */
    public static  <K,T> LoadingCache<K,Optional<T>> buildCache(Function<K,T> loader ){
        return buildCache(10 ,loader);
    }


}
